package com.dces.jx.billtest.userAdd.service;
import com.dces.jx.billtest.dto.userAdd.*;
import com.dces.jx.billtest.userAdd.dao.DcBillListZhjMapper;
import com.dces.jx.billtest.userAdd.mapper.DcBillListZhjDtoMapper;
import com.dces.jx.billtest.userAdd.model.DcBillListZhj;
import com.dces.jx.billtest.userAdd.model.Nums;
import org.apache.commons.collections4.CollectionUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xdo.common.base.service.BaseService;
import com.xdo.common.token.UserInfoToken;
import com.xdo.domain.PageParam;
import com.xdo.domain.ResultObject;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import javax.annotation.Resource;
import javax.validation.constraints.Digits;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
/**
 * generated by Generate dcits
 * Service;
 *
 * @author xdoV2.0
 * @date: 2021-9-3
 */
@Service
public class DcBillListZhjService extends BaseService<DcBillListZhj> {
    @Resource
    private DcBillListZhjMapper dcBillListZhjMapper;
    @Resource
    private DcBillListZhjDtoMapper dcBillListZhjDtoMapper;
    @Override
    public Mapper<DcBillListZhj> getMapper() {
        return dcBillListZhjMapper;
    }
    /**
     * 功能描述: grid分页查询
     *
     * @param dcBillListZhjParam
     * @param pageParam
     * @return
     */
    public ResultObject<List<DcBillListZhjDto>> selectAllPaged(DcBillListZhjParam dcBillListZhjParam, PageParam pageParam) {
        // 启用分页查询
        DcBillListZhj dcBillListZhj = dcBillListZhjDtoMapper.toPo(dcBillListZhjParam);
        Page<DcBillListZhj> page = PageHelper.startPage(pageParam.getPage(), pageParam.getLimit(), pageParam.getSortOrderContent())
                .doSelectPage(() -> dcBillListZhjMapper.getList(dcBillListZhj));
        List<DcBillListZhjDto> dcBillListZhjDtos = page.getResult().stream().map(head -> {
            DcBillListZhjDto dto = dcBillListZhjDtoMapper.toDto(head);
            return dto;
        }).collect(Collectors.toList());
		 ResultObject<List<DcBillListZhjDto>> paged = ResultObject.createInstance(dcBillListZhjDtos, (int) page.getTotal(), page.getPageNum());
        return paged;
    }
    /**
     * 功能描述:查询所有数据
     *
     * @param exportParam
     * @return
     */
    public List<DcBillListZhjDto> selectAll(DcBillListZhjParam exportParam) {
        DcBillListZhj dcBillListZhj = dcBillListZhjDtoMapper.toPo(exportParam);
        List<DcBillListZhjDto> dcBillListZhjDtos = new ArrayList<>();
        List<DcBillListZhj> dcBillListZhjs = dcBillListZhjMapper.getList(dcBillListZhj);
        if (CollectionUtils.isNotEmpty(dcBillListZhjs)) {
            dcBillListZhjDtos = dcBillListZhjs.stream().map(item -> {
                DcBillListZhjDto dto = dcBillListZhjDtoMapper.toDto(item);
                return dto;
            }).collect(Collectors.toList());
        }
        return dcBillListZhjDtos;
    }
    /**
     * 功能描述:新增
     *
     * @param model
     * @param userInfo
     * @return
     */
    public DcBillListZhjDto insert(DcBillListZhjParam model, UserInfoToken userInfo) {

        String sid = UUID.randomUUID().toString();
        DcBillListZhj dcBillListZhj = dcBillListZhjDtoMapper.toPo(model);
        dcBillListZhj.setSid(sid);
        dcBillListZhj.setInsertUser(userInfo.getUserNo());
        dcBillListZhj.setInsertTime(new Date());
        int insertStatus = dcBillListZhjMapper.insert(dcBillListZhj);
       return insertStatus > 0 ? dcBillListZhjDtoMapper.toDto(dcBillListZhj) : null;
    }
    /**
     * 功能描述:修改
     *
     * @param dcBillListZhjParam
     * @param userInfo
     * @return
     */
    public DcBillListZhjDto update(DcBillListZhjParam dcBillListZhjParam, UserInfoToken userInfo) {
        DcBillListZhj dcBillListZhj = dcBillListZhjMapper.selectByPrimaryKey(dcBillListZhjParam.getSid());
        dcBillListZhjDtoMapper.updatePo(dcBillListZhjParam, dcBillListZhj);
        dcBillListZhj.setUpdateUser(userInfo.getUserNo());
        dcBillListZhj.setUpdateTime(new Date());
        // 更新数据
        int update = dcBillListZhjMapper.updateByPrimaryKey(dcBillListZhj);
         return update > 0 ? dcBillListZhjDtoMapper.toDto(dcBillListZhj) : null;
    }
    /**
     * 功能描述:批量删除
     *
     * @param sids
     * @return
     */
    public void delete(List<String> sids, UserInfoToken userInfo) {
        dcBillListZhjMapper.deleteBySids(sids);
    }
	public int getListNumByHeadIds(List<String> sids) {
        return dcBillListZhjMapper.getListNumByHeadIds(sids);
    }

    public long getSerialNo(String headId) {
        return dcBillListZhjMapper.getSerialNo(headId);
    }



    public ResultObject queryCopGNO(CopGNoAndEmsNoParam gNoAndEmsNoParam) {
        // 去数据库查询是否存在
        if("E".equals(gNoAndEmsNoParam.getGMark())){
            int CopGNoENum = dcBillListZhjMapper.queryCopGNOE(gNoAndEmsNoParam.getCopGNo(), gNoAndEmsNoParam.getEmsNo());
            if(CopGNoENum == 0){
                return ResultObject.createInstance(false,"该商品料号未备案!");
            }
            // 就去数据库查询带出手(账)册料件/成品的备案序号、商品编码、商品名称、规格型号、申报计量单位、法定计量单位、法定第二单位
            CopGNoDto copGNoDto = dcBillListZhjMapper.queryInfoByCopGNOAndEmsNoE(gNoAndEmsNoParam.getCopGNo(), gNoAndEmsNoParam.getEmsNo());
            return ResultObject.createInstance(true,"查询成功",copGNoDto);
        }else if("I".equals(gNoAndEmsNoParam.getGMark())){
            int copGNoINum = dcBillListZhjMapper.queryCopGNOI(gNoAndEmsNoParam.getCopGNo(), gNoAndEmsNoParam.getEmsNo());
            if(copGNoINum == 0){
                return ResultObject.createInstance(false,"该商品料号未备案!");
            }
            CopGNoDto copGNoDto = dcBillListZhjMapper.queryInfoByCopGNOAndEmsNoI(gNoAndEmsNoParam.getCopGNo(), gNoAndEmsNoParam.getEmsNo());
            return ResultObject.createInstance(true,"查询成功",copGNoDto);
        }
        return ResultObject.createInstance(false,"成品标志不存在");
    }

    public int checkGNoAndCopGNo(CheckGNoAndCopNoParam param) {
        if("E".equals(param.getGMark())){
            return dcBillListZhjMapper.checkGNoAndCopGNoByE(param.getCopGNo(),param.getGNo(),param.getEmsNo());
        }
        return dcBillListZhjMapper.checkGNoAndCopGNoByI(param.getCopGNo(),param.getGNo(),param.getEmsNo());
    }

    public void deleteByHeadIds(List<String> headIds) {
        dcBillListZhjMapper.deleteByHeadIds(headIds);
    }

    public Map<String, BigDecimal> getNumSum(String headId) {
        /*
        数量汇总（仅数值）申报数量 XXXX 法定数量汇总 XXXX 法定第二数量 XXXX
        申报总价 XXXX 净重 XXXX 毛重 XXXX
         */
        Nums nums = dcBillListZhjMapper.getNums(headId);

        Map<String, BigDecimal> map = new HashMap<>();
        map.put("申报数量",nums.getQtySum());
        map.put("法定数量",nums.getQty1Sum());
        map.put("法定第二数量",nums.getQty2Sum());
        map.put("申报总价",nums.getDecTotalSum());
        map.put("净重",nums.getNetWtSum());
        map.put("毛重",nums.getGrossWtSum());
        return map;
    }

    public DcBillListZhjParam setParam(DcBillListZhjParam dcBillListZhjParam) {
        // 填充序列号
        int serialNo = dcBillListZhjMapper.getSerialNo(dcBillListZhjParam.getHeadId());
        dcBillListZhjParam.setSerialNo(serialNo);
        /**
            若“申报计量单位”与“计量单位”相同，将“第一比例因子”自动填充为1
         */
        String unit = dcBillListZhjParam.getUnit();
        String unit1 = dcBillListZhjParam.getUnit1();
        if(unit!= null  && unit.equals(unit1)) {
            BigDecimal bigDecimal = new BigDecimal("1");
            dcBillListZhjParam.setFactor1(bigDecimal);
            dcBillListZhjParam.setFactor2(bigDecimal);
            dcBillListZhjParam.setFactorWt(bigDecimal);
        }
        return dcBillListZhjParam;
    }
    public ResultObject queryGNo(GNoAndEmsNoParam gNoAndEmsNoParam) {
        if("E".equals(gNoAndEmsNoParam.getGMark())){
            //查询成品表中的数量
            int gNoENum = dcBillListZhjMapper.queryGNoE(gNoAndEmsNoParam.getGNo(), gNoAndEmsNoParam.getEmsNo());
            if(gNoENum == 0){
                return ResultObject.createInstance(false,"该商品料号未备案!");
            }
           // 就去成品表数据库查询带出手(账)册料件/成品的备案序号、商品编码、商品名称、规格型号、申报计量单位、法定计量单位、法定第二单位
            GNoDto gNoDto = dcBillListZhjMapper.queryInfoByGNOAndEmsNoE(gNoAndEmsNoParam.getGNo(),gNoAndEmsNoParam.getEmsNo());
            return ResultObject.createInstance(true,"查询成功",gNoDto);
        }else if("I".equals(gNoAndEmsNoParam.getGMark())){
            // 查询料件表中的数量
            int gNoINum =  dcBillListZhjMapper.queryGNoI(gNoAndEmsNoParam.getGNo(), gNoAndEmsNoParam.getEmsNo());
            if(gNoINum == 0){
                return ResultObject.createInstance(false,"该商品料号未备案!");
            }
            // 去料件表中查询
            GNoDto gNoDto = dcBillListZhjMapper.queryInfoByGNOAndEmsNoE(gNoAndEmsNoParam.getGNo(),gNoAndEmsNoParam.getEmsNo());
            return ResultObject.createInstance(true,"查询成功",gNoDto);
        }
        return ResultObject.createInstance(false,"成品标志不存在");
    }

    public String beforeSaveAndInsert(DcBillListZhjParam dcBillListZhjParam) {
        /**保存时校验申报总价/申报数量=企业申报单价的公式是否符合，如果不符合，
         * 提示“总价/数量与单价不等！”，确定后保存成功；取消则不保存。
         */
        BigDecimal price = dcBillListZhjParam.getDecPrice();
        BigDecimal decTotal = dcBillListZhjParam.getDecTotal();
        BigDecimal qty = dcBillListZhjParam.getQty();
        BigDecimal zero = new BigDecimal(0);
        if(qty.compareTo(zero)<= 0){
            return "数量必须大于0";
        }
        if(decTotal.compareTo(zero)<= 0){
            return "申报总价必须大于0";
        }
        if(price.compareTo(zero)<= 0){
            return "申报总价必须大于0";
        }
        MathContext mc = new MathContext(6, RoundingMode.HALF_DOWN);
        BigDecimal divide = decTotal.divide(qty, mc);
        if(divide.compareTo(price)!=0){
            return "总价/数量与单价不等！";
        }
        return  "";
    }
}
